package com.qingcloud.df.executor.launcher;

import cn.hutool.extra.spring.SpringUtil;
import com.qingcloud.df.executor.process.ProcessFactory;
import com.qingcloud.df.executor.utils.ComponentUtil;
import com.qingcloud.df.sdk.component.context.CompInstContext;
import com.qingcloud.df.sdk.component.context.CompInstRuntimeHolder;
import com.qingcloud.df.sdk.component.context.ConfigManager;
import com.qingcloud.df.sdk.component.transport.akka.AkkaTransporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;

/**
 * 独立进程长时间运行服务类组件启动器
 *
 * @author wangjinnan
 */
public class DaemonLauncher implements Launcher {
    Logger logger =  LoggerFactory.getLogger(DaemonLauncher.class);
    @Override
    public void start(CompInstContext context) {
        ProcessFactory processFactory = SpringUtil.getBean("processFactory");
        try {
            String imageName =  context.getImageName();
            Integer instanceId =  context.getId();
            Integer jobId =  context.getJobId();
            String type = String.valueOf(context.getType());
            String suffix = type + "-" + jobId + "-" + instanceId;
            String[] jarCommand = ComponentUtil.getProcessCommand(context);
            processFactory.bulidProcess(imageName,suffix,context.getInstWorkspacePath(),context.getSoftwareName(),jarCommand);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 停止组件进程  停止docker
     */
    @Override
    public void stop(CompInstContext context) {
        ProcessFactory processFactory = SpringUtil.getBean("processFactory");
        String imageName =  context.getImageName();
        Integer instanceId =  context.getId();
        Integer jobId =  context.getJobId();
        String type = String.valueOf(context.getType());
        String suffix = type + "-" + jobId + "-" + instanceId;
        processFactory.processStop(imageName,suffix);
    }
}
